<?php

class GalactusModelCalendar extends GalactusModelTelescope {

	function __construct($control) {
		GalactusModel::__construct($control);
	}

	public function addEvents($events) {
		$telescope = end($this->retrieveTelescope($events[0]));
		$this->removeAllEvents($telescope["telescope_id"]);
		array_splice($events, 0, 1);
		$i = 0;
		while($i < count($events)) {
			if(empty($events[$i]))
				array_splice($events, $i, 1);
			else ++$i;
		}
		for($i = 0; $i < count($events); $i += 3) {
			$date_start = new DateTime($events[$i]);
			$date_end = new DateTime($events[$i+1]);
			$comment = trim($events[$i+2]);
			if($date_start < $date_end) {
				$content = 'Agendamentos para o telescópio <span class="text-info">'.$telescope["name"].'</span> podem ser feitos para horários entre às <span class="text-info">'.$date_start->format('H\hi \d\e d/m/Y').'</span> e <span class="text-info">'.$date_end->format('H\hi \d\e d/m/Y').'</span>. '.$comment;
				$sql = "CALL GALACTUS_INSERT_CALENDAR(:date_start, :date_end, :user_id, :telescope_id, :comment, :title, :content)";
				$params = array(
					":date_start" => $date_start->format("Y-m-d H:i:s"),
					":date_end" => $date_end->format("Y-m-d H:i:s"),
					":user_id" => $this->control->user_id,
					":telescope_id" => $telescope["telescope_id"],
					":comment" => $comment,
					":title" => $telescope["name"].': Novos Horários',
					":content" => $content
				);
				$query = $this->query($sql, $params);
				if($query["fail"])
					throw new Exception( );
			}
		}
		echo $this->control->view->helper->alertSuccess("Operação realizada com sucesso!", URL.'REDIRECT/TELESCOPE/SHOW');
	}

	public function removeAllEvents($telescope_id) {
		$this->query(
			"DELETE c, p FROM CalendarPost cp STRAIGHT_JOIN Calendar AS c ON cp.calendar_id = c.id STRAIGHT_JOIN Post AS p ON cp.post_id = p.id WHERE c.telescope_id = :telescope_id",
			array(":telescope_id" => $telescope_id)
		);
	}

	public function removeAllSchedulings($telescope_id) {
		$sql = "
			DELETE s FROM Schedule s
			INNER JOIN Calendar AS c ON s.calendar_id = c.id
			WHERE s.user_id = :user_id AND c.telescope_id = :telescope_id
		";
		$params = array(":user_id" => $this->control->user_id, ":telescope_id" => $telescope_id);
		$this->query($sql, $params);
	}

	public function retrieveCalendar($telescope_id) {
		$query = $this->query(
			"SELECT id, date_start, date_end, comment, user_id, telescope_id FROM Calendar WHERE telescope_id = :telescope_id",
			array(':telescope_id' => $telescope_id)
		);
		if(!$query["fail"])
			return $query["result"];
		else return NULL;
	}

	public function isScheduled($telescope_id = NULL, $user_id = NULL) {
		$sql = "
			SELECT s.user_id, TIMEDIFF(s.date_end, NOW( )) AS date_diff
			FROM Schedule s INNER JOIN Calendar AS c ON s.calendar_id = c.id
			WHERE c.telescope_id = :telescope_id AND s.user_id = :user_id AND s.date_start < NOW( ) AND NOW( ) < s.date_end
		";
		$query = $this->query($sql, array(":telescope_id" => $telescope_id, ":user_id" => $user_id));
		if(!$query["fail"])
			return $query["result"];
		else return NULL;
	}

	public function retrieveSchedule($telescope_id = NULL, $user_id = NULL) {
		$sql = "";
		$params = NULL;
		if(!empty($telescope_id) || !empty($user_id)) {
			$sql = "WHERE ";
			if(!empty($telescope_id)) {
				$sql .= "c.telescope_id = :telescope_id ";
				$params[":telescope_id"] = $telescope_id;
				if(!empty($user_id)) {
					$sql .= "AND s.user_id = :user_id";
					$params[":user_id"] = $user_id;
				}
			}
			if(empty($telescope_id) && !empty($user_id)) {
				$sql .= "s.user_id = :user_id";
				$params[":user_id"] = $user_id;
			}
		}
		$sql = "
			SELECT s.date_start, s.date_end, s.user_id, s.calendar_id, c.telescope_id
			FROM Schedule s INNER JOIN Calendar AS c ON s.calendar_id = c.id
			".$sql."
			ORDER BY c.telescope_id, s.date_start
		";
		$query = $this->query($sql, $params);
		if(!$query["fail"])
			return $query["result"];
		else return NULL;
	}

	public function schedule($schedulings) {
		$telescope_id = $schedulings[0];
		array_splice($schedulings, 0, 1);
		$calendar = $this->retrieveCalendar($telescope_id);
		$this->removeAllSchedulings($telescope_id);
		if(!empty($schedulings)) {
			for($i = 0; $i < count($schedulings); ++$i) {
				$date_start = $schedulings[$i];
				$date_end = new DateTime($schedulings[$i]);
				$date_end = $date_end->modify('+15 minutes')->format('Y-m-d H:i:s');
				for($j = 0; $j < count($calendar); ++$j) {
					if($date_start >= $calendar[$j]["date_start"] && $date_end <= $calendar[$j]["date_end"]) {
						$calendar_id = $calendar[$j]["id"];
						break;
					}
				}
				$params = array(
					':date_start' => $date_start,
					':date_end' => $date_end,
					':user_id' => $this->control->user_id,
					':calendar_id' => $calendar_id
				);
				$query = $this->query("INSERT INTO Schedule VALUES (:date_start, :date_end, :user_id, :calendar_id)", $params);
				if($query["fail"])
					throw new Exception( );
			}
		}
		echo $this->control->view->helper->alertSuccess("Operação realizada com sucesso!", URL.'REDIRECT/TELESCOPE/SHOW');
	}

}

?>
